package com.aistar.controller;

import com.aistar.config.AlipayConfig;
import com.aistar.pojo.ClubActivity;
import com.aistar.pojo.ClubMember;
import com.aistar.service.ClubdetailsService;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2019/10/10.
 */
@Controller
@RequestMapping("/clubPay")
public class ClubPayController {
    @Autowired
    private ClubdetailsService clubdetailsService;


    final static Logger log = LoggerFactory.getLogger(ClubPayController.class);


    /**
     *前往支付宝第三方网关进行支付
     */
    @RequestMapping(value = "/goAlipay/{id}", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goAlipay(HttpServletRequest request, HttpServletRequest response, HttpSession session,@PathVariable("id") int cludId) throws Exception {


        String str = String.valueOf(cludId);
        session.setAttribute("clubId",str);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String userId = String.valueOf(session.getAttribute("userId")) ;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String t = sdf.format(date);
        String temp = String.valueOf(userId)+t;

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = temp;
        ClubActivity clubActivity = clubdetailsService.selectByClubIdFindPrice(cludId);
        float aa = clubActivity.getClubPrice();
        //付款金额，必填
        String total_amount = String.valueOf(aa);
        //订单名称，必填
        String subject = "报名成功";


        System.out.println("out_trade_no:"+out_trade_no);
        System.out.println("total_amount:"+total_amount);
        System.out.println("title:"+subject);


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("result :"+result);
        return result;
    }






    /*


     */
    /**
     *  支付宝同步通知页面
     */
    @RequestMapping(value = "/alipayReturnNotice")
    public String alipayReturnNotice(HttpServletRequest request, HttpServletRequest response, HttpSession session) throws Exception {



        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");
        System.out.println("22222222222222222222222222222");

        log.info("pay successfully ,支付成功, 进入同步通知接口...");
        System.out.println("支付成功后，支付宝返回的所有的数据："+ request);
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println("return notice name:"+name);
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println("return notice signVerified:"+signVerified);
        ModelAndView mv = new ModelAndView("");
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //根据俱乐部id查询是否有人报名
//            Integer clubid = 2;
            Integer clubid = Integer.parseInt(String.valueOf(session.getAttribute("clubId")));
            //查询出报名费用
            ClubActivity clubActivity = clubdetailsService.selectByClubIdFindPrice(clubid);
            //查询出报名表信息
            List<ClubMember> clubMemberList = clubdetailsService.selectByClubIdFindMember(clubid);
            Integer userId = (Integer) session.getAttribute("userId");

            if(clubMemberList.size() != 0){
                //获得集合中第一条的报名金钱总和并加上报名费用
                Float price = (clubActivity.getClubPrice());
                //获得集合中第一条的报名人数记录并加一
                Integer number = (clubMemberList.size()+1);
                Float cost = (price * number );
                //用户报名信息存入操作

                ClubMember clubMember = new ClubMember();
                clubMember.setClubId(clubid);

                clubMember.setClubUserId(userId);//暂时使用定值替代
                //存入总金额
                clubMember.setClubMemberCost(cost);

                clubMember.setClubNumber(number);

                clubdetailsService.sava(clubMember);
                clubdetailsService.updateNumber(number,clubid);
                clubdetailsService.updateCost(cost,clubid);
            }else{
                //用户报名信息存入操作
                ClubMember clubMember = new ClubMember();

                clubMember.setClubId(clubid);
                clubMember.setClubUserId(userId);
                clubMember.setClubNumber(1);
                clubMember.setClubMemberCost(clubActivity.getClubPrice());
                clubdetailsService.sava(clubMember);
            }

            /*//用户报名信息存入操作
            Integer userId = (Integer) session.getAttribute("userId");
            ClubMember clubMember = new ClubMember();
            clubMember.setClubId(1);
            clubMember.setClubUserId(16);
            clubdetailsService.sava(clubMember);*/


            System.out.println("return out_trade_no:"+out_trade_no);
            System.out.println("return trade_no:"+trade_no);
            System.out.println("return total_amount:"+total_amount);
            //	System.out.println("return productName:"+ product.getName());


            log.info("********************** 支付成功(支付宝同步通知) **********************");
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
//            log.info("* 购买产品: {}",subject );
            log.info("***************************************************************");


            mv.addObject("out_trade_no", out_trade_no);
            mv.addObject("trade_no", trade_no);
            mv.addObject("total_amount", total_amount);
//            mv.addObject("productName",subject);

        }else {
            log.info("支付, 验签失败...");
        }

        return "redirect:/clublist/list";
    }

    /**
     *
     * @Description: 支付宝异步 通知页面
     *
     */
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response, HttpSession session) throws Exception {

        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //根据俱乐部id查询是否有人报名
            /*Integer clubid = 1;
            List<ClubMember> clubMemberList = clubdetailsService.selectByClubId(clubid);*/

            //用户报名信息存入操作
            Integer userId = (Integer) session.getAttribute("userId");
            ClubMember clubMember = new ClubMember();
            clubMember.setClubId(2);
            clubMember.setClubUserId(userId);
            clubdetailsService.sava(clubMember);


            log.info("********************** 支付成功(支付宝同步通知) **********************");
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
//            log.info("* 购买产品: {}",title );
            log.info("***************************************************************");
//            }
            log.info("支付成功...");

        }else {//验证失败
            log.info("支付, 验签失败...");
        }

        return "success";
    }


}
